package com.example.dormmanage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dormmanage.dao.IMenuDao;
import com.example.dormmanage.entity.Menu;
import com.example.dormmanage.service.IMenuService;
import com.example.dormmanage.view.MenuDto;
import com.example.dormmanage.view.ResultView;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuService extends ServiceImpl<IMenuDao, Menu> implements IMenuService {

    //查询菜单列表
    public ResultView<List<MenuDto>> selectMenuList() {
        //查询父级菜单
        LambdaQueryWrapper<Menu> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Menu::getComponent, "Layout");
        List<Menu> fatherMenuList = this.list(lqw);
        //通过父级菜单查询子级菜单
        List<MenuDto> menuDtoList = fatherMenuList.stream().map(item -> {
            MenuDto menuDto = new MenuDto();
            LambdaQueryWrapper<Menu> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(Menu::getPath, item.getPath());
            List<Menu> sonMenuList = this.list(queryWrapper);
            //组合父级菜单和子级菜单
            menuDto.setFatherMenu(item);
            menuDto.setSonMenu(sonMenuList);
            return menuDto;
        }).collect(Collectors.toList());
        return ResultView.success(menuDtoList);
    }

    //添加父级菜单
    @Transactional(rollbackFor = Exception.class)
    public ResultView<String> addFatherMenu(Menu menu) {
        menu.setComponent("Layout");
        this.save(menu);
        return ResultView.success("添加父级菜单成功");
    }

    //添加子级菜单
    @Transactional(rollbackFor = Exception.class)
    public ResultView<String> addSonMenu(Menu menu) {
        this.save(menu);
        return ResultView.success("添加子级菜单成功");
    }

    //删除菜单
    @Transactional(rollbackFor = Exception.class)
    public ResultView<String> deleteMenu(Integer menuId) {
        this.removeById(menuId);
        return ResultView.success("删除成功");
    }

    //修改菜单
    public ResultView<String> updateMenu(Menu menu) {
        this.updateById(menu);
        return ResultView.success("修改成功");
    }

    //查询菜单详情
    public ResultView<Menu> selectMenuDetail(Integer menuId) {
        return ResultView.success(this.getById(menuId));
    }
}
